package com.yzw.endecoderfixed;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @Author: YangZhenWei
 * @PROJECT_NAME: nettyTeach
 * @DESCRIPTION: 客户端启动类 验证netty中的掉线重连，通过实现ChannelFutureListener来实现客户端自动重新链接
 * @USER: root
 * @DATE: 2023/2/8 22:51
 **/
public class AppClientEnDecoder {

    private final String host;
    private final int port;

    public AppClientEnDecoder(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();// io线程池
        try {
            Bootstrap bs = new Bootstrap();
            bs.group(group)
                    .channel(NioSocketChannel.class) // 实例化一个通道
                    .remoteAddress(new InetSocketAddress(host, port)) // 指定远程的ip和端口
                    .handler(new InitializerClientEnDeCoder());
            //链接获取异步操作的结果值，链接到远程节点，等待链接完成
            ChannelFuture future = bs.connect().sync();
            // 阻塞操作，closeFuture()开启了一个Channel的监听器,这期间channel在进行各种操作,直到连接断开
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new AppClientEnDecoder("127.0.0.1",18080).run();
    }
}
